package com.cgbl.service.vm

import android.app.Application
import api.WorkServiceFactory
import com.robot.base.base.vm.GLBaseViewModel
import com.robot.base.common.api.AbstractViewModelSubscriber
import com.robot.base.configs.AppConstants
import com.robot.base.model.TagListBean
import com.robot.base.model.TeamListBean
import com.robot.base.util.arouter.ARouterUtil
import me.goldze.mvvmhabit.binding.command.BindingAction
import me.goldze.mvvmhabit.binding.command.BindingCommand
import me.goldze.mvvmhabit.bus.event.SingleLiveEvent
import com.robot.base.model.BaseResponse
import java.util.regex.Pattern

class TagManagerViewModel(application: Application) : GLBaseViewModel(application) {

    val cacheList = mutableListOf<TagListBean>()

    val createTagCommand = BindingCommand<Any>(BindingAction {
        ARouterUtil.goToActivity(
            AppConstants.Router.Project.A_EDIT_TAG
        )
    })

    val managerTagCommand = BindingCommand<Any>(BindingAction {
        ARouterUtil.goToActivity(
            AppConstants.Router.Project.A_EDIT_TAG
        )
    })

    val uc = UIChangeEvent()

    class UIChangeEvent {

        val tagListDataEvent = SingleLiveEvent<List<TagListBean>>()

    }


    fun fetchLabelList() {
        WorkServiceFactory.listLabel()
            .subscribe(object : AbstractViewModelSubscriber<BaseResponse<List<TagListBean>>>(this) {
                override fun onNext(t: BaseResponse<List<TagListBean>>) {
                    cacheList.clear()
                    cacheList.addAll(t.data)
                    uc.tagListDataEvent.postValue(t.data)
                }
            })
    }

    fun fetchLabelByKeyword(keyword: String): ArrayList<TagListBean> {
        val queryResult = arrayListOf<TagListBean>()
        val pattern = Pattern.compile(keyword)
        cacheList.forEach {
            val matcher = pattern.matcher(it.labelName ?: "")
            if (matcher.find()) {
                queryResult.add(it)
            }
        }
        return queryResult
    }
}